package com.gxd.service.impl;

import com.gxd.dao.CartDao;
import com.gxd.dao.OrderDao;
import com.gxd.dao.OrderDetailDao;
import com.gxd.dao.impl.CartDaoImpl;
import com.gxd.dao.impl.OrderDaoImpl;
import com.gxd.dao.impl.OrderDetailDaoImpl;
import com.gxd.domain.Cart;
import com.gxd.domain.Order;
import com.gxd.domain.OrderDetail;
import com.gxd.domain.User;
import com.gxd.service.CartService;
import com.gxd.service.OrderService;
import com.gxd.service.UserService;
import com.gxd.util.DBUtils;
import com.gxd.util.RandomUtils;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class OrderServiceImpl implements OrderService {
    OrderDao orderDao = new OrderDaoImpl();
    OrderDetailDao orderDetailDao = new OrderDetailDaoImpl();
    @Override
    public Order selectByAid(int id) {
        return orderDao.selectByAid(id);
    }

    @Override
    public Order addOrder(int uid, String aid) {
        try {
            DBUtils.begin();
            Order order = new Order();

            CartService cartService = new CartServiceImpl();
            List<Cart> carts = cartService.findUid(uid);
            double sum =0;
            for (Cart cart : carts) {
                sum=sum+cart.getMoney();
            }
            order.setId(RandomUtils.createOrderId());
            order.setAid(Integer.parseInt(aid));
            order.setMoney(sum);
            order.setStatus("未支付");
            order.setTime(new Date());
            order.setUid(uid);
            orderDao.insertOrder(order);

            for (Cart cart : carts) {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOid(order.getId());
                orderDetail.setPid(cart.getPid());
                orderDetail.setNum(cart.getNum());
                orderDetail.setMoney(cart.getMoney());
                orderDetailDao.insertOrderDetail(orderDetail);
            }
            cartService.clearCart(uid);



            DBUtils.commit();
            return order;
        } catch (Exception e) {
            try {
                DBUtils.rollback();

            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {
            try {
                DBUtils.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
return null;

    }

    @Override
    public void paySuccess(Order order) {
        orderDao.paySuccess(order);
    }

    @Override
    public List<Order> findAll() {
        UserService userService = new UserServiceImpl();
       List<Order> order= orderDao.findAll();
        for (Order order1 : order) {
            User user = userService.findAll(order1.getUid());
            order1.setUser(user);
        }
        return order;
    }
}
